#import "TJAlertView.h"
#import "UIView+Corner.h"
@interface TJAlertViewAction()
@property(strong, nonatomic) UIColor *mTitleColor;
@property(copy, nonatomic) NSString *mTitle;
@property (nonatomic ,strong) UIColor *bgColor;
@property (nonatomic ,strong) NSAttributedString *attributeString;
@property (nonatomic, copy) void (^handlerBlock)(TJAlertViewAction *action);
@end
@implementation TJAlertViewAction
+ (instancetype)actionWithTitle:(nullable NSString *)title titleColor:(UIColor *)color handler:(void (^ __nullable)(TJAlertViewAction *action))handler {
    return [self actionWithTitle:title titleColor:color backGroudColor:[UIColor clearColor] handler:handler];
}
+ (instancetype)actionWithTitle:(nullable NSString *)title
                     titleColor:(UIColor *)color
                 backGroudColor:(UIColor *)bgColor
                        handler:(void (^ __nullable)(TJAlertViewAction *action))handler
{
    TJAlertViewAction *action = [[TJAlertViewAction alloc] init];
    action.bgColor = bgColor;
    action.mTitleColor = color;
    action.mTitle = title;
    action.handlerBlock = handler;
    return action;
}
+ (instancetype)actionWithAttributedTitle:(NSAttributedString *)title
                     titleColor:(UIColor *)color
                 backGroudColor:(UIColor *)bgColor
                        handler:(void (^ __nullable)(TJAlertViewAction *action))handler
{
    TJAlertViewAction *action = [[TJAlertViewAction alloc] init];
    action.bgColor = bgColor;
    action.mTitleColor = color;
    action.mTitle = title.string;
    action.attributeString = title;
    action.handlerBlock = handler;
    return action;
}
@end
@interface TJAlertView() <M80AttributedLabelDelegate>
@property(strong, nonatomic) UIView *mHorizontalLine;
@property(strong, nonatomic) NSMutableArray *mActionArray;
@property(assign, nonatomic) CGFloat mBtnH;
@property(copy, nonatomic) NSString *mTitle;
@property(copy, nonatomic) NSString *mSubTitle;
@property(copy, nonatomic) NSString *clickTitle;
@property(copy, nonatomic) NSString *clickSecond;
@property (nonatomic ,strong) UIButton *closeButton;
@property(nonatomic, copy) void(^clickBlock)(NSString *title);
@end
@implementation TJAlertView
+ (instancetype)alertWithTitle:(NSString * __nullable)title subTitle:(NSString * __nullable)subTitle clickTitle:(NSString *)clickTitle clickSecond:(NSString *)clickSecond click:(void(^)(NSString *title))click
{
    TJAlertView *alertView = [[TJAlertView alloc] init];
    alertView.mTitleLabel.text = title;
    alertView.clickBlock = click;
    alertView.mTitle = title;
    alertView.mSubTitle = subTitle;
    alertView.clickTitle = clickTitle;
    alertView.clickSecond = clickSecond;
    alertView.mSubLabel.text = subTitle;
    NSRange range1  = [subTitle rangeOfString:clickTitle];
    [alertView.mSubLabel addCustomLink:[NSValue valueWithRange:range1] forRange:range1];
    NSRange range2  = [subTitle rangeOfString:clickSecond];
    [alertView.mSubLabel addCustomLink:[NSValue valueWithRange:range2] forRange:range2];
    return alertView;
}
+ (instancetype)alertWithTitle:(NSString * __nullable)title subTitle:(NSString * __nullable)subTitle
{
    TJAlertView *alertView = [[TJAlertView alloc] init];
    alertView.mTitleLabel.text = title;
    alertView.mSubLabel.text = subTitle;
    alertView.mTitle = title;
    alertView.mSubTitle = subTitle;
    return alertView;
}
+ (instancetype)alertWithAttributedTitle:(NSAttributedString *)title attributedSubTitle:(NSAttributedString *)subTitle
{
    TJAlertView *alertView = [[TJAlertView alloc] init];
    alertView.mTitleLabel.attributedText = title;
    alertView.mSubLabel.attributedText = subTitle;
    alertView.mTitle = title.string;
    alertView.mSubTitle = subTitle.string;
    return alertView;
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.mBgView = [[UIView alloc] initWithFrame:UIScreen.mainScreen.bounds];
        self.mBgView.backgroundColor = UIColorFromRGBA(0x00000, 0.36);
        self.frame = CGRectMake(0, 0, Ratio(270), Ratio(150));
        self.backgroundColor  = [UIColor whiteColor];
        self.mBtnH =  Ratio(50);
        self.mTitleLabel = [[UILabel alloc] init];
        self.mTitleLabel.textColor = [UIColor color30323E];
        self.mTitleLabel.textAlignment = NSTextAlignmentCenter;
        self.mTitleLabel.font = [UIFont systemFontOfSize:Ratio(16) weight:UIFontWeightBold];
        self.mTitleLabel.numberOfLines = 0;
        [self addSubview:self.mTitleLabel];
        self.mSubLabel = [[M80AttributedLabel alloc]initWithFrame:CGRectZero];
        self.mSubLabel.textColor = [UIColor blackColor];
        self.mSubLabel.linkColor = [UIColor colorFF6C2E];
        self.mSubLabel.backgroundColor = [UIColor clearColor];
        self.mSubLabel.highlightColor = [UIColor clearColor];
        self.mSubLabel.font = [UIFont systemFontOfSize:13];
        self.mSubLabel.underLineForLink = NO;
        self.mSubLabel.contentMode = UIViewContentModeLeft;
        self.mSubLabel.textAlignment = kCTTextAlignmentLeft;
        self.mSubLabel.numberOfLines = 0;
        self.mSubLabel.delegate = self;
        [self addSubview:self.mSubLabel];
        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _closeButton.hidden = YES;
        _closeButton.frame = CGRectMake(self.ct_width-Ratio(30), Ratio(5), Ratio(24), Ratio(24));
        [_closeButton setBackgroundImage:[UIImage imageNamed:@"common_close"] forState:UIControlStateNormal];
        [_closeButton addTarget:self action:@selector(doDismissAlertView) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.closeButton];
        self.mActionArray = [NSMutableArray array];
    }
    return self;
}
#pragma mark - M80label delegate
- (void)m80AttributedLabel:(M80AttributedLabel *)label clickedOnLink:(id)linkData
{
    NSString *rangeStr =[NSString stringWithFormat:@"%@",linkData];
    NSString *title = @"";
    NSString *clickTitleLength = [NSString stringWithFormat:@"%ld",self.clickTitle.length];
    NSString *clickSecondLength = [NSString stringWithFormat:@"%ld",self.clickSecond.length];
    if ([rangeStr containsString:clickTitleLength]){
        title = _clickTitle;
    }else if ([rangeStr containsString:clickSecondLength]){
        title = _clickSecond;
    }
    if (self.clickBlock) {
        self.clickBlock(title);
    }
}
- (void)showCloseButton {
    self.closeButton.hidden = NO;
}
- (void)doAddAction:(TJAlertViewAction *)action
{
    [self.mActionArray addObject:action];
}
- (void)doShowAlertView
{
    UIView *aSuperView = [UIViewController currentTabbarController].view;
    if (!aSuperView) {
        aSuperView = [UIViewController currentViewController].view;
    }
    [self doShowAlertToSuperView:aSuperView];
}
- (void)doShowAlertToCurrentView
{
    UIView *aSuperView =UIViewController.currentNavigationController.topViewController.view ;
    if (!aSuperView) {
        aSuperView = [UIViewController currentViewController].view;
    }
    [self doShowAlertToSuperView:aSuperView];
}
- (void)doShowAlertToSuperView:(UIView *)aSuperView
{
    CGFloat aLeft = Ratio(20);
    CGFloat aLabelW = self.ct_width -  2*aLeft;
    CGFloat aTitleH = Ratio(18);
    CGFloat aTop = Ratio(15);
    CGFloat aPadding = Ratio(10);
    if (self.mTitle.length && self.mSubTitle.length) {
        CGSize maxSize = CGSizeMake(aLabelW, CGFLOAT_MAX);
        CGFloat mTitleLabelH = [self.mTitleLabel sizeThatFits:maxSize].height;
        self.mTitleLabel.frame = CGRectMake(aLeft, aTop, aLabelW, mTitleLabelH);
        CGFloat aSubLabelH = [self.mSubLabel sizeThatFits:maxSize].height;
        self.mSubLabel.frame = CGRectMake(aLeft, self.mTitleLabel.ct_bottom+aPadding, aLabelW, aSubLabelH);
    }
    if (!self.mTitle.length) {
        CGSize maxSize = CGSizeMake(aLabelW, CGFLOAT_MAX);
        CGFloat aSubLabelH = [self.mSubLabel sizeThatFits:maxSize].height;
        self.mSubLabel.frame = CGRectMake(aLeft, aLeft, aLabelW, aSubLabelH);
    }
    if (!self.mSubTitle.length) {
        CGSize maxSize = CGSizeMake(aLabelW, CGFLOAT_MAX);
        CGFloat mTitleLabelH = [self.mTitleLabel sizeThatFits:maxSize].height;
        self.mTitleLabel.frame = CGRectMake(aLeft, aLeft, aLabelW, mTitleLabelH);
    }
    self.frame = CGRectMake(0, 0, Ratio(270), self.mSubLabel.ct_bottom + aPadding + self.mBtnH);
    [self ct_getCornerViewWithRadius:Ratio(10.f)];
    self.center = CGPointMake(UIScreenWidth / 2, UIScreenHeight / 2);
    self.mHorizontalLine  = [[UIView alloc] initWithFrame:CGRectMake(0, self.ct_height - self.mBtnH - 1, self.ct_width, (1 / [UIScreen mainScreen].scale))];
    [self addSubview:self.mHorizontalLine];
    self.mHorizontalLine.backgroundColor = [UIColor color30323E];
    CGFloat aBtnW = self.ct_width  / self.mActionArray.count;
    NSMutableArray *aLineArray = [NSMutableArray array];
    for (int i = 0; i < self.mActionArray.count; i++) {
        TJAlertViewAction *action = self.mActionArray[i];
        UIButton *aBtn = [[UIButton alloc] init];
        [aBtn setTitle:action.mTitle forState:UIControlStateNormal];
        [aBtn setTitle:action.mTitle forState:UIControlStateHighlighted];
        [aBtn setTitleColor:action.mTitleColor forState:UIControlStateNormal];
        [aBtn setTitleColor:action.mTitleColor forState:UIControlStateHighlighted];
        aBtn.backgroundColor = action.bgColor;
        aBtn.titleLabel.font = [UIFont systemFontOfSize:Ratio(14)];
        aBtn.titleLabel.numberOfLines = 0;
        [aBtn sizeToFit];
        [self addSubview:aBtn];
        [aBtn setTitle:action.mTitle forState:UIControlStateNormal];
        [aBtn setTitle:action.mTitle forState:UIControlStateHighlighted];
        [aBtn setTitleColor:action.mTitleColor forState:UIControlStateNormal];
        [aBtn setTitleColor:action.mTitleColor forState:UIControlStateHighlighted];
        aBtn.tag = i;
        aBtn.frame = CGRectMake(i*aBtnW, self.ct_height-self.mBtnH, aBtnW, self.mBtnH);
        [aBtn addTarget:self action:@selector(doBtnClickAction:) forControlEvents:UIControlEventTouchUpInside];
        if (i < self.mActionArray.count - 1) {
            UIView *aLine = [[UIView alloc] initWithFrame:CGRectMake(0, aBtn.ct_top, (1 / [UIScreen mainScreen].scale), self.mBtnH)];
            aLine.ct_centerX = aBtn.ct_right;
            aLine.backgroundColor = [UIColor color30323E];
            [self addSubview:aLine];
            [aLineArray addObject:aLine];
        }
    }
    for (UIView *aLine in aLineArray) {
        [self bringSubviewToFront:aLine];
    }
    [aSuperView addSubview:self.mBgView];
    [aSuperView addSubview:self];
    self.mBgView.alpha = 0;
    self.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        self.mBgView.alpha = 1;
        self.alpha = 1;
    }];
}
-(void)doDismissAlertView{
    [UIView animateWithDuration:0.3 animations:^{
        self.mBgView.alpha = 0;
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        [self.mBgView removeFromSuperview];
    }];
};
+ (void)doDismissAlertView
{
    for (UIView *aView in UIApplication.sharedApplication.keyWindow.subviews) {
        if ([aView isKindOfClass:[self class]]) {
            TJAlertView *aPopView = (TJAlertView *)aView;
            [aPopView doDismissAlertView];
        }
    }
    for (UIView *aView in [UIViewController currentNavigationController].view.subviews) {
        if ([aView isKindOfClass:[self class]]) {
            TJAlertView *aPopView = (TJAlertView *)aView;
            [aPopView doDismissAlertView];
        }
    }
    for (UIView *aView in [UIViewController currentTabbarController].view.subviews) {
        if ([aView isKindOfClass:[self class]]) {
            TJAlertView *aPopView = (TJAlertView *)aView;
            [aPopView doDismissAlertView];
        }
    }
    for (UIView *aView in [UIViewController currentViewController].view.subviews) {
        if ([aView isKindOfClass:[self class]]) {
            TJAlertView *aPopView = (TJAlertView *)aView;
            [aPopView doDismissAlertView];
        }
    }
}
- (void)doBtnClickAction:(UIButton *)btn
{
    TJAlertViewAction *action = self.mActionArray[btn.tag];
    if (action.handlerBlock) {
        action.handlerBlock(action);
    }
    [self doDismissAlertView];
}
@end
static CGFloat NoSourceBtnTag = 0;
static CGFloat BtnHeight = 56;
static CGFloat BtnPadding = 8;
@interface TJActionSheetView()
@property(nonatomic, strong) NSMutableArray *btnArray;
@property(nonatomic, strong) NSMutableArray *lineArray;
@property (nonatomic, strong) UIButton *backgroundView;
@property(nonatomic, weak) UIButton *cancelBtn;
@end
@implementation TJActionSheetView
- (void)doRefreshCancelWithTitle:(NSString *)title
{
    [self.cancelBtn setTitle:title forState:UIControlStateNormal];
    [self.cancelBtn setTitle:title forState:UIControlStateHighlighted];
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    for (int i = 0; i < self.btnArray.count; i++) {
        UIButton *btn = self.btnArray[i];
        btn.frame = CGRectMake(0, i*BtnHeight, self.ct_width, BtnHeight);
    }
    UIView *lastLine = nil;
    for (int i = 0; i < self.lineArray.count; i++) {
        UIView *line = self.lineArray[i];
        CGFloat aLineH = (i == (self.lineArray.count-1))? BtnPadding : (1 / [UIScreen mainScreen].scale);
        line.frame = CGRectMake(0, (i + 1)*BtnHeight - kLineOffset, self.ct_width, aLineH);
        lastLine = line;
        [self bringSubviewToFront:line];
    }
    self.cancelBtn.frame = CGRectMake(0, CGRectGetMaxY(lastLine.frame), self.ct_width, BtnHeight);
}
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColor.whiteColor;
        self.btnArray = [NSMutableArray array];
        self.lineArray = [NSMutableArray array];
    }
    return self;
}
- (void)showWithSources:(NSArray<NSString *> *)sources color:(UIColor *)titleColor
{
    for (int i = 0; i < sources.count; i++) {
        NSString *title = sources[i];
        UIButton *btn = [[UIButton alloc] init];
        [btn setTitle:title forState:UIControlStateNormal];
        [btn setTitle:title forState:UIControlStateHighlighted];
        [btn setTitleColor:titleColor forState:UIControlStateNormal];
        [btn setTitleColor:titleColor forState:UIControlStateHighlighted];
        btn.backgroundColor = [UIColor whiteColor];
        btn.titleLabel.font = [UIFont systemFontOfSize:Ratio(17)];
        [btn sizeToFit];
        btn.tag = i+1;
        [self.btnArray addObject:btn];
        [self addSubview:btn];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = UIColorFromRGB(0xeeeeee);
        [self.lineArray addObject:line];
        [self addSubview:line];
    }
    UIButton *aBtn = [[UIButton alloc] init];
    [aBtn setTitle:@"Cancel" forState:UIControlStateNormal];
    [aBtn setTitle:@"Cancel" forState:UIControlStateHighlighted];
    [aBtn setTitleColor:titleColor forState:UIControlStateNormal];
    [aBtn setTitleColor:titleColor forState:UIControlStateHighlighted];
    aBtn.backgroundColor = [UIColor whiteColor];
    aBtn.titleLabel.font = [UIFont systemFontOfSize:Ratio(17)];
    [aBtn sizeToFit];
    aBtn.tag = NoSourceBtnTag;
    [self addSubview:aBtn];
    [aBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    self.cancelBtn = aBtn;
    self.frame = CGRectMake(0, 0, UIScreenWidth, (self.btnArray.count + 1) * BtnHeight + BtnPadding + kAdaptBottomH(0));
    [self ct_getTopCornerWithRatio:12.f];
    [self alert];
}
- (void)showWithSources:(NSArray *)sources
{
    [self showWithSources:sources color:UIColorFromRGB(0x222222)];
}
#pragma mark - action
- (void)btnClick:(UIButton *)btn
{
    [self dismiss];
    if (self.btnClickBlock) {
        self.btnClickBlock(btn.tag, btn.currentTitle);
    }
}
#pragma mark - alert
- (void)alert
{
    self.ct_top = UIScreenHeight;
    UIView *aKeyWindow = [UIApplication sharedApplication].keyWindow;
    [aKeyWindow addSubview:self.backgroundView];
    [aKeyWindow addSubview:self];
    self.backgroundView.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundView.alpha = 1;
        self.ct_top = UIScreenHeight - self.ct_height;
    }];
}
- (void)dismiss
{
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundView.alpha = 0;
        self.ct_top = UIScreenHeight;
    } completion:^(BOOL finished) {
        [self.backgroundView removeFromSuperview];
        [self removeFromSuperview];
    }];
    if (self.closedBlock) {
        self.closedBlock();
    }
}
- (void)backgroundViewClick
{
    [self dismiss];
}
#pragma mark - get / set
- (UIButton *)backgroundView
{
    if (!_backgroundView) {
        _backgroundView = [[UIButton alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [_backgroundView addTarget:self action:@selector(backgroundViewClick) forControlEvents:UIControlEventTouchUpInside];
        _backgroundView.backgroundColor = UIColorFromRGBA(0x000000, 0.6);
        _backgroundView.alpha = 0;
    }
    return _backgroundView;
}
- (void)setMMaskViewColor:(UIColor *)mMaskViewColor
{
    _mMaskViewColor = mMaskViewColor;
    self.backgroundView.backgroundColor = mMaskViewColor;
}
@end
